package com.qihoo.finance.fake.variety.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ctrip.framework.apollo.ConfigService;
import com.qihoo.finance.fake.variety.VarietyEnum;
import com.qihoo.finance.fake.variety.VarietyService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.support.MockInvoker;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

@Service
public class FixedVarietyBaseApolloIpServiceImpl implements VarietyService {
    Logger logger = LogManager.getLogger(FixedVarietyBaseApolloIpServiceImpl.class);

    @Override
    public Object populate(String interfaceName, Method method, String mockValue) throws Exception {
        String methodName = method.getName();

        Type[] returnTypes;
        Type returnType = method.getGenericReturnType();
        if(returnType instanceof ParameterizedType){
            returnTypes = ((sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl)returnType).getActualTypeArguments();
        }else {
            returnTypes = new Type[]{returnType};
        }

        String apolloValue = ConfigService.getConfig("variety")
                .getProperty(RpcContext.getContext().getRemoteHost(), JSON::parseObject, new JSONObject())
                .getString(interfaceName + "#" + methodName);
        logger.info("fixed_apollo_ip获取配置key: {}, value: {}", interfaceName + "#" + methodName, apolloValue);
        apolloValue = StringUtils.defaultString(apolloValue, mockValue);
        if (StringUtils.isNotBlank(apolloValue)) {
            return MockInvoker.parseMockValue(apolloValue, returnTypes);
        } else {
            if (returnTypes.length > 0 && "com.qihoo.finance.msf.api.domain.Response".equals(returnTypes[0].getTypeName())) {
                return new com.qihoo.finance.msf.api.domain.Response().fail("", String.format("%s%s%s%s%s", "未加载到", interfaceName, "#", methodName, "对应的fake配置"));
            }
            logger.info("{}#{}固定值mock配置结果为空", interfaceName, methodName);
        }
        return null;
    }

    @Override
    public VarietyEnum getVarietyType() {
        return VarietyEnum.FIXED_APOLLO_IP;
    }
}
